const axios = require('axios');
const puppeteer = require('puppeteer');
const assert = require('assert');
const fs = require("fs-extra");
const ProgressBar = require("progress");

/**
 * 代码来源 https://www.cnblogs.com/TianFang/p/9064409.html
 */


/**
 * 
 * @param {string} url 谷歌浏览器的调试接口信息地址
 * 
 * @returns {string} 谷歌浏览器的调试接口地址
 */
async function getChromeDebuggerUrl(url) {
    let rsp = await axios.get(url);
    return rsp.data.webSocketDebuggerUrl;
}

const utils = {};

/**
 * @param {string} ip
 * @param {int} port
 * 
 * @return {Browser} 通过ip和port连接已打开调试的chrome浏览器
 * 
 */
utils.connectBrowser = async function(ip, port) {
    let versionUrl = "http://" + ip + ":" + port + "/json/version";
    let webSocketDebuggerUrl = await getChromeDebuggerUrl(versionUrl);
    const browser = await puppeteer.connect({
        browserWSEndpoint: webSocketDebuggerUrl
    });
    return browser;
}

/**
 * 添加request事件的page，如果不需要就直接调用browser.newPage
 */
utils.newPage = async function(browser, options) {
    const page = await browser.newPage();
    if (options != undefined) {
        if (options.noPicture == true) {
            await page.setRequestInterception(true);
            page.on('request', interceptedRequest => {
                if (interceptedRequest.url().endsWith('.png') || interceptedRequest.url().endsWith('.jpg'))
                    interceptedRequest.abort();
                else
                    interceptedRequest.continue();
            });
        }
    }
    return page;
}

/**
 * 获取页面缓存列表
 */
utils.getResourceTree = async function(page) {
    var resource = await page._client.send('Page.getResourceTree');
    return resource.frameTree;
}

/**
 * 获取页面缓存的内容
 */
utils.getResourceContent = async function(page, url) {
    const { content, base64Encoded } = await page._client.send(
        'Page.getResourceContent',
        { frameId: String(page.mainFrame()._id), url }
    );
    assert.equal(base64Encoded, true);
    return content;
};

utils.downloadCachedResource = async function(page, url, imgPath) {
    let content = await utils.getResourceContent(page, url);
    let buf = Buffer.from(content, "base64");
    fs.writeFileSync(imgPath, buf, "base64");
}

utils.buildFilePath = function(url, downloadPath, fileName) {
    if (fileName == undefined) {
        fileName =  url.split('/').slice(-1);
    }
    let imgPath = `${downloadPath}/${fileName}`;
    return imgPath;
}

/**
 * @param page
 * @param selector
 * 
 * 模拟点击跳转
 * 
 */
utils.clickAndOpenPage = async function(page, selector) {
    await Promise.all([
        page.waitForNavigation(),
        page.click(selector),
    ]);
}

/**
 * 模拟点击跳转到新的Tab页面
 */
utils.clickAndOpenNewTab = async function(browser, page, selector) {
    const [newPage, ] = await Promise.all([
        new Promise(resolve => browser.once('targetcreated', target => resolve(target.page()))),
        page.click(selector)
    ]);

    return newPage;
}

/**
 * 跳转到新的Tab页面
 */
utils.clickAndOpenNewTab2 = async function(browser, url) {
    const target = await browser.waitForTarget(t=>t.url() == url);
    const newPage = await target.page();
    return newPage;
}

utils.sleep = async function(time) {
  return new Promise((resolve) => setTimeout(resolve, time));
}

utils.progressBar = function(total) {
    /*
    带颜色的进度条
    const green = '\u001b[42m \u001b[0m';
    const red = '\u001b[41m \u001b[0m';
    const bar = new ProgressBar("[ :bar ]", {
        complete: green,
        incomplete: red,
        total: total
    });
    */
    //const bar = new ProgressBar('progress: [:bar]', { total: total, width: 10, complete: '*' });

    const bar = new ProgressBar(':percent eta: :eta downloading :current/:total :file', {
        total: total
    });

    return function(str) {
        bar.tick({
            'file': str
        });
        if (bar.complete) {
            console.log("\ncomplete\n");
        }
    }
}

utils.progressBar2 = function(total) {

}


module.exports = utils;